<?php
/**
 * 系统登录、退出
 */
declare (strict_types = 1);

namespace app\admin\controller\admin;

use app\admin\model\admin\AdminUser;
use app\BaseController;
use EasyWeChat\Factory;
use think\facade\Config;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;

class System extends BaseController
{
    /**
     * 后台管理员登录
     */
    public function login()
    {
        $admin = new AdminUser();
        //是否已经登录
        if ($admin->isLogin()) {
            $this->redirect('index');
        }

        if (Request::isAjax()){
            //获取数据
            $data = Request::post();
            //验证
            $validate = new \app\admin\validate\admin\Admin();
            if(!$validate->scene('login')->check($data)) {
                return json(['code' => 0, 'msg' => $validate->getError()]);
            }
            //是否存储7天
            if (!isset($data['remember'])) {
                $data['remember'] = 0;
            }

            if (false == $admin->login($data['username'],$data['password'],$data['remember'])){
                return json(['code' => 0, 'msg' => $admin->error]);
            }
            $success = (string)url('admin.index/index');
            return json(['code' => 1, 'msg' => '登录成功','url'=>$success]);
        }
        return View::fetch();
    }

    /**
     * 退出登陆
     */
    public function logout()
    {
        $userModel = new AdminUser();
        if( $userModel->logout() ){
            return $this->resp('退出登录');
        }
    }

    /***
     * 微信登录授权
     */
    public function wxOAuth()
    {
        // 未登录
        if (empty($_SESSION['admin'])) {
            //easyWechat
            $app = Factory::officialAccount(Config::get('wx.open_terrace'));
            $oauth = $app->oauth;
            // 这里不一定是return，如果你的框架action不是返回内容的话你就得使用
            $oauth->redirect()->send();
        }
    }

    /**
     * 微信登录授权验证
     * @param $code
     * @return mixed|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function oauthCallback($code)
    {
        $app = Factory::officialAccount(Config::get('wx.open_terrace'));
        $oauth = $app->oauth;
        $user = $oauth->user(null)->toArray();
        if (isset($user['original']['errcode']) && $user['original']['errcode']) {
            return $this->error('授权失败，请重试');
        }
        if ($user) {
            $userExit = \app\admin\model\admin\Admin::where('terrace_openid', $user['id'])->find();
            //去绑定页
            if (!$userExit) {
                Session::set('admin_user_wx_register',
                    ['terrace_openid' => $user['id'],
                    'unionid' => $user['original']['unionid'],
                    'headimgurl' => $user['avatar'],
                        ]);
                View::assign(['avatar' => $user['avatar']]);
                return View::fetch('wx_register');
            }
            if ($userExit['status'] != 1){
                return $this->error('用户不存在或被禁用！');
            }

            // 缓存信息
            $data = [
                'id' => $userExit->id,
                'username' => $userExit->username,
                'nickname' => $userExit->nickname,
                'password' => $userExit->password,
                'menu' => $userExit->permissions($userExit->id),
                'campus' => $userExit->campus_id
            ];
            Session::set('admin', $data);
            return redirect('https://erp.yd1995.com/admin.php');
        }
    }

    public function wxRegister()
    {
        if (!Request::isAjax()){
            $this->error('请求错误');
        }

        $admin = new \app\admin\model\admin\Admin;
        //获取数据
        $data = Request::post();
        //验证
        $validate = new \app\admin\validate\admin\Admin;
        if(!$validate->scene('login')->check($data)) {
            $this->error($validate->getError());
        }
        if ($admin->login($data['username'],$data['password'])){
            $data = [
                'username' => trim($data['username']),
                'password' => substr(md5(trim($data['password'])),8,16),
                'status' => 1
            ];
            //验证用户
            $admin = $admin->where($data)->find();
            $adminUserWx = Session::get('admin_user_wx_register');
            if (!$adminUserWx){
                $this->error('授权过期，请重新扫码');
            }
            $isExeit = Db::table('admin_user')->where('unionid', $adminUserWx['unionid'])->find();
            if ($isExeit){
                $this->error('该微信号已绑定其他账号');
            }
            $admin->terrace_openid = $adminUserWx['terrace_openid'];
            $admin->unionid = $adminUserWx['unionid'];
            $admin->headimgurl = $adminUserWx['headimgurl'];
            $admin->public_openid = $adminUserWx['public_openid'];
            $admin->save();
            // 缓存信息
            $data = [
                'id' => $admin->id,
                'username' => $admin->username,
                'nickname' => $admin->nickname,
                'password' => $admin->password,
                'menu' => $admin->permissions($admin->id),
                'campus' => $admin->campus_id
            ];
            Session::set('admin', $data);
            $this->success('绑定成功');
        }
        $this->error('用户名或密码错误');
    }
}
